package com.coderman.business.service.imp;

import com.coderman.business.converter.StudentConverter;
import com.coderman.business.mapper.*;
import com.coderman.business.service.IStudentService;
import com.coderman.business.service.base.AbstractServiceImpl;
import com.coderman.common.error.SystemCodeEnum;
import com.coderman.common.error.SystemException;
import com.coderman.common.model.student.Student;
import com.coderman.common.model.student.StudentClass;
import com.coderman.common.vo.student.StudentVO;
import com.coderman.common.vo.system.PageVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class StudentServiceImpl extends AbstractServiceImpl<StudentMapper, Student, Integer> implements IStudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private StudentClassMapper studentClassMapper;
    @Autowired
    private PayMentMapper payMentMapper;
    @Autowired
    private StudentScoreMapper studentScoreMapper;
    @Autowired
    private ObtainEmpMapper obtainEmpMapper;
    @Autowired
    private AccommodationMapper accommodationMapper;
    @Override
    public PageVO<Student> findList(Integer pageNum, Integer pageSize, StudentVO studentVO) {
        PageHelper.startPage(pageNum,pageSize);
//        Example o = new Example(Student.class);
//        String studentName = studentVO.getStudentName();
////        Integer classId = studentVO.getClassid();//班级编号
//        String phone = studentVO.getStudentPhone();
//        String enrolTime = studentVO.getEnrolTime();//入学时间
//        Integer studentStatus = studentVO.getStudentStatus();//学生状态
//        Example.Criteria criteria = o.createCriteria();
//        if(!StringUtils.isEmpty(studentName)){
//            criteria.andLike("studentName","%"+studentName+"%");
//        }
////        if(classId!=null){
////            criteria.andEqualTo("classId",classId);
////        }
//        if(!StringUtils.isEmpty(phone)){
//            criteria.andEqualTo("studentPhone",phone);
//        }
//        if(!StringUtils.isEmpty(enrolTime)){
//            criteria.andEqualTo("enrolTime",enrolTime);
//        }
//        if(studentStatus!=null){
//            criteria.andEqualTo("studentStatus",studentStatus);
//        }
        //List<Student> studentList= studentMapper.selectByExample(o);
        Student student = new Student();
        BeanUtils.copyProperties(studentVO,student);
        student.setClassName(studentVO.getClassName());
        List<Student> studentList = studentMapper.selectStudentList(student);
        PageInfo<Student> info=new PageInfo<>(studentList);
        return new PageVO<>(info.getTotal(),studentList);
    }

    /**
     * 添加学生信息
     *
     * @param studentVO
     */
    @Override
    public void add(StudentVO studentVO) {
        Student student = new Student();
        BeanUtils.copyProperties(studentVO,student);
        int result = studentMapper.insert(student);

        //插入数据时需要判断关系表是否已存在，存在则不需加添加
        addStudentClassInfo(student,result);
    }

    /**
     * 编辑学生信息
     *
     * @param id
     * @return
     */
    @Override
    public StudentVO edit(Integer id) throws SystemException {
        //Student student = studentMapper.selectByPrimaryKey(id);
        Student student = studentMapper.selectStudentById(id);
        if(student==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"编辑学生信息不存在");
        }
        StudentVO studentVO = StudentConverter.converterToStudentVO(student);
        return studentVO;
    }

    /**
     * 更新学生信息
     *
     * @param id
     * @param studentVO
     */
    @Override
    public void update(Integer id, StudentVO studentVO) throws SystemException {
        //Student dbStudent = studentMapper.selectByPrimaryKey(id);
        Student dbStudent = studentMapper.selectStudentById(id);
        if(dbStudent==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"编辑的学生信息不存在");
        }
        Student student = new Student();
        BeanUtils.copyProperties(studentVO,student);
        student.setStudentId(id);
        //int result = studentMapper.updateByPrimaryKeySelective(student);
        int result = studentMapper.updateStudent(student);
        //更新学生的同时，判断下班级如果不为空则添加一条数据到“班级学生关系表”
        //插入数据时需要判断关系表是否已存在，存在则不需加添加
        addStudentClassInfo(student,result);
    }

    /**
     * 删除学生信息
     *
     * @param id
     */
    @Override
    public void delete(Integer id) throws SystemException {
        //Student student = studentMapper.selectByPrimaryKey(id);
        Student student = studentMapper.selectStudentById(id);
        if(student==null){
            throw new SystemException(SystemCodeEnum.PARAMETER_ERROR,"要删除的学生信息不存在");
        }
        //int result = studentMapper.deleteStudentById(id);
        //删除操作（先删除缴费，成绩表，就业表，住宿表）
        //缴费表
//        PayMent payMent = new PayMent();
//        payMent.setStudentid(id);
//        payMentMapper.delete(payMent);
//        //成绩表
//        StudentScore studentScore = new StudentScore();
//        studentScore.setStudentId(id);
//        studentScoreMapper.delete(studentScore);
//        //就业表
//        ObtainEmp obtainEmp = new ObtainEmp();
//        obtainEmp.setStudentid(id);
//        obtainEmpMapper.delete(obtainEmp);
//        //住宿表
//        Accommodation accommodation = new Accommodation();
//        accommodation.setStudentId(id);
//        accommodation.del
        //最后再删除学生表，这里要用到事物，后面再加
        //删除功能先保留，学生不作删除
        studentMapper.deleteStudentById(id);

    }

    /**
     * 所有学生信息
     *
     * @return
     */
    @Override
    public List<StudentVO> findAllVO() {
        List<Student> students = studentMapper.selectAll();
        //转vo
        List<StudentVO> studentVOS = new ArrayList<>();
        if (!CollectionUtils.isEmpty(students)) {
            for (Student student : students) {
                StudentVO u = new StudentVO();
                BeanUtils.copyProperties(student, u);
                Example o = new Example(Student.class);
                o.createCriteria().andEqualTo("studentId",student.getStudentId())
                        .andNotEqualTo("type",0);
                studentVOS.add(u);
            }
        }
        return studentVOS;
    }

    /**
     * 全部学生信息
     *
     * @return
     */
    @Override
    public List<Student> findAll() {
        return studentMapper.selectAll();
    }

    @Override
    public String getStuNameById(Integer id) {
        return studentMapper.getStuNameById(id);
    }

    @Override
    public List<StudentVO> findStuListByParams(Map map) {
        Example o = new Example(Student.class);
        String studentName = (String) map.get("studentName");
        Example.Criteria criteria = o.createCriteria();
        if(!StringUtils.isEmpty(studentName)){
            criteria.andLike("studentName","%"+studentName+"%");
        }
        List<Student> students = studentMapper.selectByExample(o);
        List<StudentVO> studentVOS = new ArrayList<>();
        students.stream().forEach(student -> {
            StudentVO studentVO = StudentConverter.converterToStudentVO(student);
            studentVOS.add(studentVO);
        });
        return studentVOS;
    }

    /**
     * 往学生班级关系表中添加一条数据
     * @param student  学生对象
     */
    public void addStudentClassInfo(Student student,int result){
        if(result>0) {
            if (student.getClassId() != null) {
                //先查出学生关系表是否存在数据
                StudentClass studentClass = studentClassMapper.getClassByStudentId(student.getStudentId());
                if (studentClass == null) {
                    StudentClass st = new StudentClass();
                    st.setClassId(student.getClassId());
                    st.setStudentId(student.getStudentId());
                    studentClassMapper.insert(st);
                }
            }
        }
    }
}
